package net.wanho.filter;

import cn.hutool.json.JSONUtil;
import net.wanho.properties.IgnoreWhiteProperties;
import net.wanho.vo.AjaxResult;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

/**
 * 网关鉴权，实现统一的身份认证
 */
// @Component
public class AuthFilter implements GlobalFilter, Ordered {
 
    @Resource
    private IgnoreWhiteProperties ignoreWhite;

    /**
     * 过滤器的核心方法
     * @param exchange 用于操作请求/响应的相关信息
     * @param chain 过滤器链，用于调用下一个过滤器或目标资源
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("AuthFilter.filter................");

        /**
         * 跳过不需要校验的白名单
         */
        String url = exchange.getRequest().getURI().getPath();
        if (ignoreWhite.getWhites().contains(url)){
            return chain.filter(exchange); // 放行
        }

        /**
         * 获取token，并判断是否为空
         */
        String token = exchange.getRequest().getHeaders().getFirst("Authorization");
        if(StringUtils.isEmpty(token)){
            ServerHttpResponse res = exchange.getResponse();
            String jsonStr = JSONUtil.toJsonStr(AjaxResult.fail(HttpStatus.UNAUTHORIZED.value(), "请先登录再操作！"));
            DataBuffer buffer = res.bufferFactory().wrap( jsonStr.getBytes(StandardCharsets.UTF_8));
            res.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
            return res.writeWith(Mono.just(buffer));
        }


        return chain.filter(exchange); // 放行，调用下一个过滤器或目标资源
    }

    /**
     * 定义过滤器的优先级：值越小，优先级越高
     */
    @Override
    public int getOrder() {
        return 0;
    }
}